<template>
	<view v-if="projectDetails">
		<view class="top-box">
			<uni-nav-bar leftIcon="left" :leftIcon2="leftIcon2" title="详情" statusBar :border="false" :leftWidth="40"
				:leftWidth2="40" backgroundColor="#FFFFFF" @clickLeft="handleBack"
				@clickLeft2="handleBackHome"></uni-nav-bar>
		</view>
		<banner :slider="slider" />
		<view class="top-content">
			<text class="title">{{ projectDetails.name }}</text>
			<view class="tag-list">
				<tagText v-for="(item, index) in projectDetails.marks" :key="index" :itemData="item"
					:itemIndex="index" />

			</view>
			<view class="bottom-box">
				<text class="strength-desc">{{ projectDetails.area }}/{{ projectDetails.project_stage }}/{{
                    projectDetails.financing_amount
                }}</text>
				<image class="smallIcon" src="@/static/project/ic_eye.png" mode="heightFix"></image>
				<text class="strength-size">{{ projectDetails.num_read }}</text>
				<view style="flex: 1;" />
				<view v-if="!projectDetails.is_collect" class="collectionBtn" @click="addStuff">
					<image class="smallIcon" src="@/static/project/ic_start_us.png" mode="heightFix"></image>
					<text class="strength-size">收藏</text>
				</view>
				<view v-if="projectDetails.is_collect" class="collectionBtn" @click="cancelCollection">
					<image class="smallIcon" src="@/static/project/ic_start_s.png" mode="heightFix"></image>
					<text class="strength-size">收藏</text>
				</view>
			</view>
		</view>
		<view class="w-content">
			<baseTitle title="项目详情" />
			<view v-if="htmlContent" class="richText">
				<u-parse :content="htmlContent"></u-parse>
			</view>
		</view>
		<view class="w-content">
			<baseTitle title="项目核心技术/核心产品" />
			<view v-if="projectDetails?.innovation" class="richText">
				<u-parse :content="projectDetails?.innovation"></u-parse>
			</view>
		</view>

		<view class="w-content" style="margin-bottom: 40rpx;">
			<baseTitle title="项目属性" />
			<attributeItem title="项目编号" :desc="projectDetails.project_no" />
			<attributeItem title="所属行业" :desc="projectDetails.cateinfo?.name" />
			<attributeItem title="核心业务" :desc="projectDetails.core_business" />
			<attributeItem title="融资方式" :desc="projectDetails.financial_mode" />
			<attributeItem title="轮次" :desc="projectDetails.project_stage" />
			<attributeItem title="融资金额(万元)" :desc="projectDetails.financing_amount" />
			<attributeItem title="所属区域" :desc="projectDetails.area" />
		</view>
		<!-- 授权弹窗 -->
		<uni-popup ref="popup" type="bottom" background-color="#fff">
			<view class="authorizedDialog">
				<text class="companyName">客满</text>
				<text class="desc">请您授权头像昵称信息，您授权的信息将受到严格保护请放心使用。</text>
				<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar" style="border: none;
		background: white;">
					<view v-if="!avatarUserUrl" class="unauthorized">
						<image class="avatar" src="@/static/personalCenter/ic_not_logged_in.png" mode="widthFix">
						</image>
						<text class="desc">获取头像</text>
					</view>
					<view v-else class="unauthorized">
						<image class="avatar" :src="avatarUserUrl" mode="widthFix"></image>
						<text class="desc"></text>
					</view>
				</button>
				<input name="nickName" v-model="nickName" type="nickname" class="inputNickName" placeholder="请输入昵称"
					@blur="getNickName" />

				<text class="authorizedBtn" @click="handleCheckUserInfo">确认授权</text>
			</view>

		</uni-popup>
	</view>
</template>
<script setup>
	import {
		ref
	} from 'vue'

	import {
		navigateTo
	} from '@/utils/util.js'
	import {
		onLoad,
		onShow,
		onShareAppMessage
	} from '@dcloudio/uni-app'

	import {
		login,
		getProjectDetails,
		addCollect,
		cancelCollect
	} from '@/api/index.js'
	import banner from './components/banner.vue'
	import tagText from '@/components/tagText.vue'
	import baseTitle from './components/baseTitle.vue'
	import attributeItem from './components/attributeItem.vue'
	const htmlContent = ref()
	const projectDetails = ref({})
	const projectId = ref()
	const slider = ref()
	const popup = ref()
	const nickName = ref()
	const avatarUserUrl = ref()
	const userInfoCheck = ref(false)
	const leftIcon2 = ref()

	onLoad((options) => {
		if (options.id) {
			projectId.value = options.id
			if (options.shared && options.shared == 6) {
				leftIcon2.value = "home"
				uni.login({
					success: (res) => {
						console.log('login', res);
						loginWithCode(res.code)
					}
				})
			} else {
				getData()
			}
		}
	})

	onShow(() => {
		if (projectId.value) {
			let userInfo = uni.getStorageSync('userInfo') || {};
			checkUserInfo(userInfo)
			if (userInfoCheck.value) {
				if (userInfo.vip_code && userInfo.vip_code > 0) {
					if (projectDetails.value == {}) {
						getData()
					}

				} else {
					navigateTo({
						url: `/pages/dataManagement/index`
					})
				}
			} else {
				navigateTo({
					url: `/pages/dataManagement/index`
				})
				// openAuthorizedDialog()
			}
		}
	})

	const loginWithCode = async (code) => {
		let res = await login({
			'code': code
		})
		if (res?.code) {
			console.log(res.data);
			console.log(res.data.token.token);
			uni.setStorageSync('token', res.data.token.token)
			getData()
		}
	}
	onShareAppMessage((res) => {
		return {
			title: projectDetails.value.name || '客满',
			path: `/pages/details/index?id=${projectId.value}&shared=6`
		}
	})

	const getData = async () => {
		let res = await getProjectDetails({
			code: projectId.value
		})
		if (res?.code) {
			console.log(res.data);
			projectDetails.value = res.data || {}
			if (projectDetails.value) {
				htmlContent.value = projectDetails.value.content
				slider.value = projectDetails.value.slider || []
			}
		}
	}
	const addStuff = async () => {
		let res = await addCollect({
			code: projectId.value
		})
		if (res?.code) {
			projectDetails.value.is_collect = 1
			uni.showToast({
				title: res.info || "收藏成功！"
			})
		}
	}

	const cancelCollection = async () => {
		let res = await cancelCollect({
			code: projectId.value
		})
		if (res?.code) {
			projectDetails.value.is_collect = 0
			uni.showToast({
				title: res.info || "取消收藏成功！"
			})
		}
	}
	const handleBack = () => {
		uni.navigateBack()
	}

	const handleBackHome = () => {
		uni.reLaunch({
			url: "/pages/index/index"
		})
	}

	// 用户信息




	const checkUserInfo = (userInfo) => {
		if (userInfo && userInfo.headimg) {
			avatarUserUrl.value = userInfo.headimg
			nickName.value = userInfo.nickname
			userInfoCheck.value = true
		} else {
			userInfoCheck.value = false
		}
	}

	const openAuthorizedDialog = () => {
		popup.value.open()
	}

	const onChooseAvatar = (e) => {
		const {
			avatarUrl
		} = e.detail
		// avatarUserUrl.value = avatarUrl
		uploadAvatar(avatarUrl)
	}
	const getTokenStorage = () => {
		let token = ''
		try {
			token = uni.getStorageSync('token')
		} catch (e) {}
		return token
	}
	const uploadAvatar = (filePath) => {
		// 调用uni.uploadFile方法上传头像  
		// 全局默认的头信息（方便以后扩展）
		const defaultHeader = {}

		const token = getTokenStorage()
		defaultHeader['api-token'] = token
		defaultHeader['api-name'] = 'wxapp'
		uni.uploadFile({
			url: 'https://qiwu.jfia.cn/data/api.auth.center/upload', // 替换为你的服务器接口地址  
			filePath: filePath,
			header: defaultHeader,
			name: 'file', // 根据你的服务器接口要求设置  
			formData: {
				// 如果需要，可以在这里添加其他表单数据  
			},
			success: (res) => {
				// 处理上传成功的逻辑
				const data = JSON.parse(res.data || "")
				console.log('头像上传成功:', data.code);
				if (data.code) {
					avatarUserUrl.value = data.data.url
				} else {
					uni.showToast({
						icon: "none",
						title: data.info
					})
				}
			},
			fail: (err) => {
				// 处理上传失败的逻辑  
				console.error('头像上传失败:', err);
				uni.showToast({
					icon: "none",
					title: "头像上传失败"
				})
			}
		});
	}


	const getNickName = (e) => {
		nickName.value = e.detail.value
	}

	const handleCheckUserInfo = () => {
		console.log(avatarUserUrl.value);
		console.log(nickName.value);
		const isCheck = avatarUserUrl.value && nickName.value
		if (isCheck) {
			setMineUserInfo()
			popup.value.close()
		}
	}



	const getMineUserInfo = async () => {
		let res = await getUserInfo()
		if (res?.code) {
			console.log("getUserInfo=>", res.data);
			uni.setStorageSync("userInfo", res.data)
			checkUserInfo(res.data)
			if (userInfoCheck.value) {
				navigateTo({
					url: `/pages/dataManagement/index`
				})
			}
		}
	}


	const setMineUserInfo = async () => {
		let res = await updateUserInfo({
			headimg: avatarUserUrl.value,
			nickname: nickName.value,
		})
		if (res?.code) {
			console.log("getUserInfo=>", res.data);
			getMineUserInfo()
		}
	}
</script>
<style lang="scss" scoped>
	.top-box {
		position: sticky;
		top: 0;
		z-index: 9;
	}

	.top-content {
		background: white;
		width: 100%;
		display: flex;
		flex-direction: column;

		.title {
			margin: 0 20rpx;
			font-weight: 600;
			font-size: 34rpx;
			color: #061612;
		}

		.tag-list {
			margin: 20rpx 20rpx 0;
			display: flex;
			flex-direction: row;
			align-items: center;
		}

		.bottom-box {
			display: flex;
			flex-direction: row;
			align-items: center;

			.strength-desc {
				margin-left: 25rpx;
				margin-top: 24rpx;
				margin-right: 40rpx;
				margin-bottom: 24rpx;
				font-size: 26rpx;
				color: #8D8D8D;
				text-overflow: ellipsis;
				overflow: hidden;
			}

			.strength-size {
				margin-right: 22rpx;
				font-size: 26rpx;
				color: #8D8D8D;
			}

			.smallIcon {
				width: 24rpx;
				margin-right: 8rpx;
				height: 24rpx;
			}

			.collectionBtn {
				height: 46rpx;
				display: flex;
				flex-direction: row;
				align-items: center;
				margin-right: 22rpx;
				padding: 0 21rpx;
				background: #F8F8F8;
				border-radius: 23rpx;

				.strength-size {
					font-size: 26rpx;
					margin: 0;
					color: #5A5A5A;
				}

				.smallIcon {
					width: 24rpx;
					margin-right: 7rpx;
					height: 24rpx;
				}

				&:active {
					opacity: 0.7;
				}
			}

		}
	}

	.w-content {
		background: white;
		display: flex;
		margin-top: 20rpx;
		flex-direction: column;

		.richText {
			width: 710rpx;
			display: flex;
			flex-direction: column;
			margin: 0 20rpx 20rpx;
		}
	}
</style>